﻿package gear.game {
	import flash.display.DisplayObject;
	import flash.display.Sprite;

	/**
	 * DepthSort 深度排序器
	 * 
	 * @author bright
	 * @version 20101015
	 */
	public final class DepthSort {
		private var _target : Sprite;

		private function compare(source : DisplayObject, target : DisplayObject):int {
			if(source.y < target.y) {
				return -1;
			} else if(source.y > target.y) {
				return 1;
			} else if(source.x < target.x) {
				return -1;
			} else if(source.x > target.x) {
				return 1;
			} else {
				return 0;
			}
		}

		public function DepthSort(target : Sprite) {
			_target = target;
		}

		/**
		 * add 使用二分搜索算法插入显示对象
		 * 
		 * @param value DisplayObject
		 */
		public function add(value : DisplayObject):void {
			if(_target.numChildren == 0) {
				trace("first=0");
				_target.addChild(value);
				return;
			}
			var left : int = 0;
			var right : int = _target.numChildren - 1;
			while(left <= right) {
				var mid : int = (left + right) / 2;
				var d : int = compare(value, _target.getChildAt(mid));
				trace(left, right, mid, d);
				if(d == -1) {
					right = mid - 1;
				} else if(d == 1) {
					left = mid + 1;
				} else {
					break;
				}
			}
			trace("depth=", mid);
			_target.addChildAt(value, mid);
		}
	}
}
